<template>
  <PageWrapper v-loading="loading" loading-tip="加载中...">
    <div class="p-4 p-4-tag">
      <div class="tag">
        <div class="form-box">
          <BasicForm @register="registerForm" />
          <div class="btns">
            <a-button class="btns-one" @click="handleResetFields" v-if="hasPermission('12-1-reset')"
              >重置</a-button
            >
            <a-button type="primary" @click="throttleSubmit" v-if="hasPermission('12-1-save')"
              >提交</a-button
            >
          </div>
        </div>
      </div>
    </div>
  </PageWrapper>
</template>

<script setup lang="ts">
  import { usePermission } from '/@/hooks/web/usePermission';
  import { PageWrapper } from '/@/components/Page';
  import { ref, onMounted } from 'vue';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form/index';
  import { useDebounceFn } from '@vueuse/core';
  import { getFormErrorMessage } from '/@/utils/index';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { checkIp } from '/@/utils/index';
  import {
    getSystemConfig,
    setSystemConfig,
    getApiServer,
    setApiServer,
    getWebAppConfig,
    setWebAppConfig,
  } from '/@/api/system/index';

  // 表单内容
  const schemas: FormSchema[] = [
    {
      field: 'divider-basic',
      component: 'Divider',
      label: '路径设定',
      colProps: {
        span: 24,
      },
      componentProps: {
        orientationMargin: '10px',
      },
    },
    {
      field: 'ProjectDefaultPath',
      component: 'Input',
      label: '工程默认路径：',
      colProps: {
        span: 14,
      },
      rules: [
        {
          required: true,
          message: '请输入工程默认路径',
          trigger: ['change', 'blur'],
        },
      ],
    },
    {
      field: 'RecordDefaultPath',
      component: 'Input',
      label: '日志默认路径：',
      colProps: {
        span: 14,
      },
      rules: [
        {
          required: true,
          message: '请输入日志默认路径',
          trigger: ['change', 'blur'],
        },
      ],
    },
    {
      field: 'divider-basic',
      component: 'Divider',
      label: 'API服务',
      colProps: {
        span: 24,
      },
      componentProps: {
        orientationMargin: '10px',
      },
    },
    {
      field: 'DefaultPort',
      component: 'Input',
      label: '默认端口：',
      colProps: {
        span: 14,
      },
      componentProps: {
        disabled: true,
      },
      rules: [
        {
          required: true,
          validator: validatorPort,
          trigger: ['change', 'blur'],
        },
      ],
    },
    {
      field: 'FrontAccessPort',
      component: 'Input',
      label: '前端访问端口：',
      colProps: {
        span: 14,
      },
      rules: [
        {
          required: true,
          validator: validatorPort,
          trigger: ['change', 'blur'],
        },
      ],
    },
    {
      field: 'IpAddress',
      component: 'Input',
      label: 'IP地址：',
      colProps: {
        span: 14,
      },
      rules: [
        {
          required: true,
          message: '请输入IP地址',
          trigger: ['change', 'blur'],
        },
      ],
    },
    {
      field: 'divider-basic',
      component: 'Divider',
      label: '日志',
      colProps: {
        span: 24,
      },
      componentProps: {
        orientationMargin: '10px',
      },
    },
    {
      field: 'MonitorIp',
      component: 'Input',
      label: '监听IP：',
      colProps: {
        span: 14,
      },
      rules: [
        {
          required: true,
          validator: async (_rule, value) => checkIp(value, '监听IP'),
          trigger: ['change', 'blur'],
        },
      ],
    },
    {
      field: 'Port',
      component: 'Input',
      label: '端口：',
      colProps: {
        span: 14,
      },
      rules: [
        {
          required: true,
          validator: validatorPort,
          trigger: ['change', 'blur'],
        },
      ],
    },
  ];
  const { hasPermission } = usePermission();
  let loading = ref<boolean>(false);
  let oldValue = {};
  const [registerForm, { validateFields, setFieldsValue }] = useForm({
    labelWidth: 130,
    schemas: schemas,
    showActionButtonGroup: false,
    actionColOptions: {
      span: 24,
    },
  });
  const { createMessage } = useMessage();
  const { t } = useI18n();
  onMounted(async () => {
    loading.value = true;
    try {
      let resByConfig = await getSystemConfig();
      let resByServer = await getApiServer();
      let resByWeb = await getWebAppConfig();
      let setValue = {
        ProjectDefaultPath: resByConfig.ProjectConfig?.ProjectDirPath || '',
        RecordDefaultPath: resByConfig.LogConfig?.LocalLogPath || '',
        DefaultPort: resByServer.WebAPIConfig?.PORT || '',
        FrontAccessPort: resByWeb.ListeningAddress?.Port || '',
        IpAddress: resByServer.WebAPIConfig?.IP || '',
        MonitorIp: resByConfig.LogConfig?.IP || '',
        Port: resByConfig.LogConfig?.Port || '',
      };
      oldValue = setValue;
      setFieldsValue(setValue);
      loading.value = false;
    } catch (error) {
      loading.value = false;
    }
  });
  const throttleSubmit = useDebounceFn(handleSubmint, 500);
  async function validatorPort(rule, value) {
    console.log(`output->rule`, rule);
    if (['', null, undefined].indexOf(value) >= 0) {
      /* eslint-disable-next-line */
      let text = `请输入${
        rule.field === 'DefaultPort'
          ? '默认端口'
          : rule.field === 'FrontAccessPort'
          ? '前端访问端口'
          : '端口：'
      }`;
      return Promise.reject(text);
    }

    let reg = /^\+?[1-9]\d*$/;
    if (!reg.test(value)) {
      /* eslint-disable-next-line */
      return Promise.reject('只能输入正整数');
    }
    return Promise.resolve();
  }
  async function handleSubmint() {
    try {
      let res = await validateFields();
      console.log('passing', res);
      let LogConfigs = {
        ProjectDefaultPath: 'ProjectConfig.ProjectDirPath',
        RecordDefaultPath: 'LogConfig.LocalLogPath',
        MonitorIp: 'LogConfig.IP',
        Port: 'LogConfig.Port',
      };
      let WebAPIConfig = {
        DefaultPort: 'WebAPIConfig.PORT',

        IpAddress: 'WebAPIConfig.IP',
      };
      let ListeningAddresss = {
        FrontAccessPort: 'ListeningAddress.Port',
      };

      let LogConfigParams: any = [];
      let WebAPIParams: any = [];
      let WebAppParams: any = [];
      for (let key in LogConfigs) {
        LogConfigParams.push({
          Key: LogConfigs[key],
          Value: res[key],
        });
      }
      for (let key in WebAPIConfig) {
        WebAPIParams.push({
          Key: WebAPIConfig[key],
          Value: res[key],
        });
      }
      for (let key in ListeningAddresss) {
        WebAppParams.push({
          Key: ListeningAddresss[key],
          Value: res[key],
        });
      }
      await setSystemConfig([LogConfigParams]);
      await setApiServer([WebAPIParams]);
      await setWebAppConfig([WebAppParams]);
      createMessage.success(t('layout.setting.operatingTitle'));
    } catch (error: any) {
      console.log('not passing', error);
      getFormErrorMessage(error);
    }
  }
  function handleResetFields() {
    // resetFields();
    setFieldsValue(oldValue);
  }
</script>

<style lang="less" scoped>
  .p-4-tag {
    width: 100%;
    height: 100%;
    padding: 0px !important;
    .tag {
      position: relative;
      overflow: hidden;
      height: 100%;
      background-color: #fff;
      ::v-deep(.ant-col-14){
        margin: 10px 0;
      }
      .pagination-box {
        z-index: 9;
        padding: 10px 5px;
        box-sizing: border-box;
        position: absolute;
        width: 100%;
        bottom: 0;
        left: 0;
        right: 0;
        background-color: #fff;
      }
    }
    .form-box {
      padding: 5px;

      ::v-deep(.ant-form-item) {
        margin: 0 5px;
        margin-bottom: 8px;
      }
    }
    .btn-box {
      display: flex;
      align-items: center;

      .btn-box-item {
        margin: 0 5px;
      }
    }
    .tag::after {
      content: '';
      display: block;
      width: 100%;
      height: 45px;
    }
    // .form-box {
    //   width: 100%;
    //   height: 100%;
    //   background-color: #fff;
    // }
  }

  .btns {
    width: 100%;
    padding-left: 130px;
    box-sizing: border-box;
    margin-top: 10px;

    .btns-one {
      margin-right: 10px;
    }
  }
</style>
